<template>
  <div class="app-container">
    <!-- 搜索条件区域 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <!-- 题库选择 -->
      <el-select
        v-model="queryParams.bId"
        filterable
        placeholder="所属题库"
        clearable
        class="filter-item"
        style="width: 200px"
        @change="bankChange"
      >
        <el-option
          v-for="item in bankData"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
      <!-- 章节选择 -->
      <el-select
        v-model="queryParams.cpId"
        filterable
        placeholder="所属章节"
        clearable
        class="filter-item"
        style="width: 200px"
      >
        <el-option
          v-for="item in chapterData"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
      <el-form-item label="题目类型" prop="type">
        <el-select
          v-model="queryParams.type"
          filterable
          placeholder="请选择题目类型"
          clearable
          class="filter-item"
          style="width: 200px"
          :disabled="son"
        >
          <el-option key="0" label="单选题" value="单选题" />
          <el-option key="1" label="多选题" value="多选题" />
          <el-option key="2" label="判断题" value="判断题" />
          <el-option key="3" label="填空题" value="填空题" />
          <el-option key="4" label="简答题" value="简答题" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5" v-if="!son">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['teacher:question:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5" v-if="!son">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['teacher:question:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5" v-if="!son">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['teacher:question:remove']"
        >删除</el-button>
      </el-col>
      <el-button
        v-if="son"
        class="filter-item"
        style="margin-left: 10px;"
        type="success"
        icon="el-icon-check"
        @click="$emit('close-event', $refs.multipleTable.selection)"
      >
        确定添加
      </el-button>
      <el-button-group v-if="!son" class="filter-item" style="float:  right">
        <el-button icon="el-icon-upload2" @click="importVisible = true">导入</el-button>
        <el-button icon="el-icon-download" @click="handleExport">导出</el-button>
      </el-button-group>
    </el-row>

    <!-- 问题表格 -->
    <el-table v-loading="loading" :data="questionList" @selection-change="handleSelectionChange" ref="multipleTable">
      <el-table-column type="selection" width="55" align="center"  />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column prop="content" label="内容" align="center" width="600" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-link v-if="!son" type="primary" @click="handleUpdate(scope.row)">{{
              scope.row.content
            }}</el-link>
          <span v-else style="color: #409eff">{{ scope.row.content }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属题库" align="center" prop="bankName" />
      <el-table-column label="所属章节" align="center" prop="chapterName" />
      <el-table-column label="题目类型" align="center" prop="type" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" v-if="!son">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['teacher:question:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['teacher:question:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改问题对话框 -->
    <el-drawer
      :title="curQuestion == null ? '增加题目' : '修改题目'"
      :visible.sync="drawerVisable"
      size="60%"
      :wrapper-closable="false"
      :destroy-on-close="true"
    >
      <questionForm
        v-if="drawerVisable"
        :cur-question="curQuestion"
        @close-event="drawerVisable = false;
        getList()"
      />
    </el-drawer>

    <!-- 导入框 -->
    <el-dialog
      title="导入试题"
      :visible.sync="importVisible"
      width="30%"
    >
      <el-row>
        <el-button type="warning" @click="downloadImport">下载导入模板</el-button>
        <el-upload
          class="upload-demo"
          drag
          action="http://localhost:8093/system/upload/uploadExcel"
          multiple
          align="center"
          style="margin-top: 30px"
          :on-success="handleUploadSuccess"
        >
          <i class="el-icon-upload" />
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
      </el-row>
    </el-dialog>
  </div>
</template>


<script>
import waves from '@/directive/waves' // waves directive
import {
  addQuestion,
  delQuestion, getQuestion,
  listQuestion, updateQuestion
} from '@/api/teacher/question'
import {
  listBank
} from '@/api/teacher/bank'
import {
  listChapter
} from '@/api/teacher/chapter'
import questionForm from './questionForm.vue'

export default {
  name: "Question",
  components: { questionForm },
  directives: { waves },
  props: {
    son: {
      type: Boolean,
      required: false,
      default: false
    },
    typeId: {
      type: Number,
      required: false,
      default: null
    },
    excludeIdList: {
      type: Array,
      required: false,
      default: null
    },
    bId: {
      type: Number,
      required: true,
      default: 1
    }
  },
  data: function () {
    return {
      // 根路径
      baseURL: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 当前问题
      curQuestion: null,
      // 问题表格数据
      questionList: [],
      // 题库数据
      bankData: [],
      // 章节数据
      chapterData: [],
      // 抽屉框显示
      drawerVisable: false,
      // 导入框显示
      importVisible: false,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        bId: null,
        cpId: null,
        type: null,
        remark: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {

      }
    }
    },
    created(){
      if (this.son) {
        // 确定类型
        let type = null
        if (this.son) {
          switch (this.typeId) {
            case 0:
              type = '单选题'
              break
            case 1:
              type = '多选题'
              break
            case 2:
              type = '判断题'
              break
            case 3:
              type = '填空题'
              break
            case 4:
              type = '简答题'
              break
          }
          this.queryParams.type = type
        }
        // 确定排除
        this.queryParams.excludeIdList = this.excludeIdList
      }
      this.getList();
        // 从服务器获得题库信息
        listBank().then((res) => {
          this.bankData = res.rows
        })

        listChapter({bId: this.bId}).then(response => {
          if (response.code === 200) {
            this.tableData = response.data
          }
        });
    }
  ,
    methods: {
      /** 查询问题列表 */
      getList()
      {
        this.loading = true;
        listQuestion(this.queryParams).then(response => {
          this.questionList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },

      // 取消按钮
      cancel()
      {
        this.open = false;
        this.reset();
      }
    ,
      // 表单重置
      reset()
      {
        this.form = {
          id: null,
          bId: null,
          cpId: null,
          type: null,
          content: null,
          image: null,
          answer: null,
          anImg: null,
          analyse: null,
          anaChart: null,
          remark: null
        };
        this.resetForm("form");
      }
    ,
      handleUpdate(row){
        this.curQuestion = row
        this.drawerVisable = true
        this.title = "修改问题"

      },
      handleQuery()
      {
        this.queryParams.pageNum = 1;
        this.getList();
      }
    ,
      /** 重置按钮操作 */
      resetQuery()
      {
        this.resetForm("queryForm");
        this.handleQuery();
      }
    ,
      // 多选框选中数据
      handleSelectionChange(selection)
      {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      }
    ,
      /** 新增按钮操作 */
      handleAdd()
      {
        this.reset();
        this.curQuestion = null;
        this.drawerVisable = true

        this.title = "添加问题";
      }
    ,

      /** 提交按钮 */
      submitForm()
      {
        // this.$refs["form"].validate(valid => {
        //   if (valid) {
            if (this.form.id != null) {
              updateQuestion(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addQuestion(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
        //   }
        // });
      }
    ,
      /** 删除按钮操作 */
      handleDelete(row)
      {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除问题编号为"' + ids + '"的数据项？').then(function () {
          return delQuestion(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      },
      /** 导出按钮操作 */
      handleExport()
      {
        this.download('teacher/question/export', {
          ...this.queryParams
        }, `question_${new Date().getTime()}.xlsx`)
      },
      downloadImport() {
        window.open('https://wangpeng-imgsubmit.oss-cn-hangzhou.aliyuncs.com/Exam/%E9%A2%98%E7%9B%AE%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx')
      },
      handleUploadSuccess() {
        // 上传成功
        this.$message.success('导入成功！')
        this.importVisible = false
        this.getList()
      },
      bankChange() {
        this.queryParams.cpId = null
        if (this.queryParams.bId == null || this.queryParams.bId === '') {
          this.chapterData = null
        } else {
          listChapter({ bId: this.queryParams.bId }).then((res) => {
            this.chapterData = res.data
          })
        }
      },
    }
  };
</script>
